const Service = require('egg').Service;

class CircleService extends Service {
    // 创建圈子（仅管理员）
    async create(circleData) {
        const { ctx } = this;

        // 检查圈子名称是否已存在
        const existingCircle = await ctx.model.Circle.findOne({
            where: { name: circleData.name }
        });
        if (existingCircle) {
            throw new Error('圈子名称已存在');
        }

        // 创建圈子
        const circle = await ctx.model.Circle.create({
            ...circleData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        return circle;
    }

    // 获取圈子列表（分页）
    async getCircles(query) {
        const { ctx } = this;
        const { page = 1, pageSize = 5, type, keyword } = query;

        const where = {};
        if (type) where.type = type;
        if (keyword) {
            where.name = { [ctx.app.Sequelize.Op.like]: `%${keyword}%` };
        }

        const options = {
            where,
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'ASC']]
        };

        const { count, rows } = await ctx.model.Circle.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 根据ID获取圈子详情
    async getCircleById(circleId) {
        const { ctx } = this;

        const circle = await ctx.model.Circle.findByPk(circleId);

        if (!circle) {
            throw new Error('圈子不存在');
        }

        return circle;
    }

    // 更新圈子信息（仅管理员）
    async updateCircle(circleId, updateData) {
        const { ctx } = this;

        // 检查圈子是否存在
        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        // 如果更新名称，检查是否重复
        if (updateData.name && updateData.name !== circle.name) {
            const existingCircle = await ctx.model.Circle.findOne({
                where: { name: updateData.name }
            });
            if (existingCircle) {
                throw new Error('圈子名称已存在');
            }
        }

        // 更新圈子信息
        await circle.update({
            ...updateData,
            updated_at: new Date()
        });

        return circle;
    }

    // 删除圈子（仅管理员）
    async deleteCircle(circleId) {
        const { ctx } = this;

        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        // 检查是否有成员
        const memberCount = await ctx.model.UserCircle.count({
            where: { circle_id: circleId }
        });
        if (memberCount > 0) {
            throw new Error('圈子还有成员，无法删除');
        }

        // 检查是否有帖子
        const postCount = await ctx.model.CirclePost.count({
            where: { circle_id: circleId }
        });
        if (postCount > 0) {
            throw new Error('圈子还有帖子，无法删除');
        }

        await circle.destroy();
        return true;
    }

    // 获取热门圈子
    async getHotCircles(limit = 10) {
        const { ctx } = this;

        const circles = await ctx.model.Circle.findAll({
            limit: parseInt(limit),
            order: [
                ['member_count', 'DESC'],
                ['post_count', 'DESC']
            ]
        });

        return circles;
    }

    // 搜索圈子方法
    async searchCircles(keyword, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 5, type, searchType = 'name' } = query;

        const where = {};

        // 根据搜索类型构建查询条件
        if (keyword) {
            if (searchType === 'name') {
                where.name = { [ctx.app.Sequelize.Op.like]: `%${keyword}%` };
            } else if (searchType === 'type') {
                where.type = { [ctx.app.Sequelize.Op.like]: `%${keyword}%` };
            } else if (searchType === 'both') {
                where[ctx.app.Sequelize.Op.or] = [
                    { name: { [ctx.app.Sequelize.Op.like]: `%${keyword}%` } },
                    { type: { [ctx.app.Sequelize.Op.like]: `%${keyword}%` } }
                ];
            }
        }

        if (type) where.type = type;

        const options = {
            where,
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['member_count', 'DESC']]
        };

        const { count, rows } = await ctx.model.Circle.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 更新圈子成员数量
    async updateMemberCount(circleId, change) {
        const { ctx } = this;

        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        if (change > 0) {
            await circle.increment('member_count');
        } else if (change < 0 && circle.member_count > 0) {
            await circle.decrement('member_count');
        }

        return await circle.reload();
    }

    // 更新圈子帖子数量
    async updatePostCount(circleId, change) {
        const { ctx } = this;

        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        if (change > 0) {
            await circle.increment('post_count');
        } else if (change < 0 && circle.post_count > 0) {
            await circle.decrement('post_count');
        }

        return await circle.reload();
    }

    // 获取圈子统计信息
    async getCircleStats() {
        const { ctx } = this;

        // 获取总圈子数
        const totalCircles = await ctx.model.Circle.count();

        // 按类型统计
        const typeStats = await ctx.model.Circle.findAll({
            attributes: [
                'type',
                [ctx.app.Sequelize.fn('COUNT', '*'), 'count']
            ],
            group: ['type']
        });

        // 获取成员最多的前5个圈子
        const topCircles = await ctx.model.Circle.findAll({
            attributes: ['circle_id', 'name', 'member_count', 'post_count'],
            order: [['member_count', 'DESC']],
            limit: 5
        });

        return {
            totalCircles,
            typeStats,
            topCircles
        };
    }

    // 用户加入圈子
    async joinCircle(userId, circleId) {
        const { ctx } = this;

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 验证圈子是否存在
        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        // 检查用户是否已经加入该圈子
        const existingJoin = await ctx.model.UserCircle.findOne({
            where: {
                user_id: userId,
                circle_id: circleId
            }
        });

        if (existingJoin) {
            throw new Error('已经加入该圈子');
        }

        // 创建加入记录
        const userCircle = await ctx.model.UserCircle.create({
            user_id: userId,
            circle_id: circleId,
            joined_at: new Date()
        });

        // 更新圈子成员数量
        await this.updateMemberCount(circleId, 1);

        return userCircle;
    }

    // 用户退出圈子
    async leaveCircle(userId, circleId) {
        const { ctx } = this;

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 验证圈子是否存在
        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        // 检查用户是否已经加入该圈子
        const userCircle = await ctx.model.UserCircle.findOne({
            where: {
                user_id: userId,
                circle_id: circleId
            }
        });

        if (!userCircle) {
            throw new Error('未加入该圈子');
        }

        // 删除加入记录
        await userCircle.destroy();

        // 更新圈子成员数量
        await this.updateMemberCount(circleId, -1);

        return true;
    }

    // 获取用户加入的圈子列表
    async getUserJoinedCircles(userId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 10 } = query;

        // 验证用户是否存在
        const user = await ctx.model.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        const options = {
            where: { user_id: userId },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [{
                model: ctx.model.Circle,
                as: 'circle',
                attributes: ['circle_id', 'name', 'type', 'description', 'member_count', 'post_count']
            }],
            order: [['joined_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.UserCircle.findAndCountAll(options);

        // 提取圈子信息
        const circles = rows.map(item => ({
            ...item.circle.toJSON(),
            joined_at: item.joined_at
        }));

        return {
            list: circles,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取圈子的成员列表
    async getCircleMembers(circleId, query) {
        const { ctx } = this;
        const { page = 1, pageSize = 20 } = query;

        // 验证圈子是否存在
        const circle = await ctx.model.Circle.findByPk(circleId);
        if (!circle) {
            throw new Error('圈子不存在');
        }

        const options = {
            where: { circle_id: circleId },
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            include: [{
                model: ctx.model.User,
                as: 'user',
                attributes: ['user_id', 'phone', 'email', 'nickname', 'avatar', 'created_at']
            }],
            order: [['joined_at', 'ASC']]
        };

        const { count, rows } = await ctx.model.UserCircle.findAndCountAll(options);

        // 提取用户信息
        const members = rows.map(item => ({
            ...item.user.toJSON(),
            joined_at: item.joined_at
        }));

        return {
            list: members,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取用户与圈子的关系状态
    async getUserCircleStatus(userId, circleIds) {
        const { ctx } = this;

        if (!Array.isArray(circleIds) || circleIds.length === 0) {
            return {};
        }

        const userCircles = await ctx.model.UserCircle.findAll({
            where: {
                user_id: userId,
                circle_id: circleIds
            },
            attributes: ['circle_id', 'joined_at']
        });

        // 构建状态映射
        const statusMap = {};
        userCircles.forEach(item => {
            statusMap[item.circle_id] = {
                joined: true,
                joined_at: item.joined_at
            };
        });

        // 为未加入的圈子设置状态
        circleIds.forEach(circleId => {
            if (!statusMap[circleId]) {
                statusMap[circleId] = {
                    joined: false,
                    joined_at: null
                };
            }
        });

        return statusMap;
    }
    async removeMember(circleId, userId) {
        const { ctx } = this;

        try {
            // 直接删除用户圈子关系
            const result = await ctx.model.UserCircle.destroy({
                where: {
                    user_id: userId,
                    circle_id: circleId
                }
            });

            if (result === 0) {
                throw new Error('用户未加入该圈子或关系不存在');
            }

            // 更新成员数量
            const circle = await ctx.model.Circle.findByPk(circleId);
            if (circle && circle.member_count > 0) {
                await circle.decrement('member_count');
            }

            return true;
        } catch (error) {
            console.error('移除成员错误:', error);
            throw error;
        }
    }

}

module.exports = CircleService;